<template>
    <div class="fillContain">
        <head-top></head-top>

        <el-form :inline="true" ref="form"  size="mini" label-width="">
            <el-form-item label="数据源名称：">
                <el-input placeholder="请输入数据源名称" v-model="datasourcename" style="width: 200px" clearable></el-input>
            </el-form-item>
            <el-form-item label="数据源类型：">
                <el-select v-model="datasourcetype"  placeholder="请选择数据源类型" style="width: 200px" clearable>
                    <el-option label="MYSQL" value="1"></el-option>
                    <el-option label="ORACLE" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-button icon="el-icon-search" size="mini" type="primary" @click="search()">查询</el-button>
            <el-button icon="el-icon-plus" size="mini" type="primary" @click="addData('datasource')">新增</el-button>
        </el-form>
        <el-table :data="tableData" border style="width: 100%;margin-top: 30px">
            <el-table-column prop="id" label="标识" width="100"></el-table-column>
            <el-table-column prop="name" label="数据源名称" width="120"></el-table-column>
            <el-table-column prop="jdbcUrl" label="数据源链接字符串" width="500"></el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="editData(scope.row)">编辑
                    </el-button>
                    <el-button size="mini" type="danger" icon="el-icon-circle-close" @click.native.prevent="deleteSubmitForm(scope.$index,scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 15, 20, 25]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="counts">
            </el-pagination>
        </div>

        <el-dialog title="新增数据源" :visible.sync="addDatacenterDialogVisible" width="50%" center>
            <el-form :model="datasource" :rules="rules" status-icon ref="datasource" label-width="100px">
                <el-form-item label="数据源名称" prop="name">
                    <el-input type="text" prop="name" v-model="datasource.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="数据源类型" prop="datasourceType">
                    <el-select v-model="datasource.datasourceType" clearable placeholder="请选择数据源类型" @change="editDriftStatus">
                        <el-option label="MySQL" value="1"></el-option>
                        <el-option label="ORACLE" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据源驱动类" prop="driverClass">
                    <el-input type="text" prop="driverClass" v-model="datasource.driverClass" auto-complete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="数据源连接字符串" prop="jdbcUrl">
                    <el-input type="text" prop="jdbcUrl" v-model="datasource.jdbcUrl"></el-input>
                </el-form-item>
                <el-form-item label="登陆用户名" prop="datasourceUser">
                    <el-input type="text" v-model="datasource.datasourceUser"></el-input>
                </el-form-item>
                <el-form-item label="数据源登录密码" prop="password">
                    <el-input type="text" v-model="datasource.password"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="testConnect('datasource')">测试连接</el-button>
                    <el-button type="primary" @click="addSubmitForm('datasource')">提交</el-button>
                    <el-button @click="addDatacenterDialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>

        </el-dialog>

        <el-dialog title="修改数据源" :visible.sync="centerDialogVisible" width="50%" center @closed="cancel('datasource')">

            <el-form :model="datasource" :rules="rules" status-icon ref="datasource" label-width="100px">
                <el-form-item label="数据源ID" prop="id" style="display: none">
                    <el-input type="text" prop="id" v-model="datasource.id" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="数据源名称" prop="name">
                    <el-input type="text" prop="name" v-model="datasource.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="数据源类型" prop="datasourceType">
                    <el-select v-model="datasource.datasourceType" clearable placeholder="请选择数据源类型">
                        <el-option v-for="item in options" :key="item.value" :label="item.label"
                                   :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据源驱动类" prop="driverClass">
                    <el-input type="text" prop="driverClass" v-model="datasource.driverClass"
                              auto-complete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="数据源连接字符串" prop="jdbcUrl">
                    <el-input type="text" prop="jdbcUrl" v-model="datasource.jdbcUrl"></el-input>
                </el-form-item>
                <el-form-item label="登陆用户名" prop="datasourceUser">
                    <el-input type="text" v-model="datasource.datasourceUser"></el-input>
                </el-form-item>
                <el-form-item label="数据源登录密码" prop="password">
                    <el-input type="text" v-model="datasource.password"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="testConnect('datasource')">测试连接</el-button>
                    <el-button type="" @click="editSubmitForm('datasource')">提交</el-button>
                    <el-button @click="cancel('datasource')">取消</el-button>
                </el-form-item>
            </el-form>

        </el-dialog>

    </div>


</template>

<script>
    import {addDataSource, getDataSourceList, testConnectDataSource, editDataSource,deleteDataSource,DataSourceList} from '@/api/getData'
    import HeadTop from '@/views/main-components/HeadTop.vue'
    import {verificateDataSourceEdit} from '@/api/user'

    export default {
        components: {
            HeadTop,
        },

        data() {
            return{
                options: [{value: '1', label: 'MySQL'},{value: '2', label: 'ORACLE'}],
                datasourcetype: '',
                datasourcename: '',
                tableData: [],
                datasource: {
                    id: '',
                    name: '',
                    datasourceType:'',
                    driverClass: '',
                    jdbcUrl: '',
                    datasourceUser: '',
                    password: ''

                },
                currentRow: null,
                counts: 0,
                currentPage: 1,
                pageSize: 15,
                rules: {
                    name: [{required: true, message: '请填写数据源名称', trigger: 'blur'}],
                    driverClass: [{required: true, message: '请填写数据源驱动类', trigger: 'blur'}],
                    jdbcUrl: [{required: true, message: '请填写数据源连接字符串', trigger: 'blur'}],
                    datasourceUser: [{required: true, message: '登陆用户名', trigger: 'blur'}],
                    password: [{required: true, message: '登陆密码', trigger: 'blur'}],
                },
                addModalFlag: false,
                centerDialogVisible: false,
                addDatacenterDialogVisible: false,
                dataList: [],
            }

        },
        created() {
            this.getUserInfo();
        },
        methods: {

            //监听页面变化
            handleSizeChange(val) {
                this.pageSize = val;
                console.log(val);
                this.search();
            },
            //监听页面选择变化
            handleCurrentChange(val) {
                this.currentPage = val;
                this.search();
            },
            editDriftStatus(){
                if(this.datasource.datasourceType=="2"){
                    this.datasource.driverClass='oracle.jdbc.driver.OracleDriver';
                }
                if(this.datasource.datasourceType=="1"){
                    this.datasource.driverClass='com.mysql.jdbc.Driver';
                }

            },
            cancel(forName){
                this.centerDialogVisible = false;
                this.$refs[forName].resetFields();
            },

            /**
             *获取所有数据源数据信息
             */
            getList() {
                getDataSourceList().then(response => response.json()).then(data => {
                    this.dataList = data;
                    this.tableData = data;
                })

            },

            /**
             *判断用户是否拥有页面权限
             */
            async getUserInfo(){
                let STAFF_ID=this.$utils.getUrlKey("STAFF_ID");
                let OPERATE_TIME=this.$utils.getUrlKey("OPERATE_TIME");
                let TRADE_ID=this.$utils.getUrlKey("TRADE_ID");
                let SIGNMSG=this.$utils.getUrlKey("SIGNMSG");
                let channel='dataSource';
                if (STAFF_ID=="1"||this.pression==false){
                    this.search();
                }else{
                    let userinfo= await this.getUser(STAFF_ID,OPERATE_TIME,TRADE_ID,SIGNMSG,channel);
                    if (userinfo.isPression){
                        this.search();
                    }else{
                        this.$router.push({path: '/404',query:{ msg:userinfo.msg}});
                    }
                }

            },
            /**
             *查询方法
             */
            async  search(){
                let value=this.datasourcetype;
                let input=this.datasourcename;
                //let param ={driverClass:value,name:input};
                let param = new URLSearchParams();
                param.append("type", value);
                param.append("name", input);
                param.append('pageSize', this.pageSize);
                param.append('pageNumber', this.currentPage);
                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                let reply =await DataSourceList(param);
                this.tableData=reply.rows;
                this.counts=reply.total;
                loading.close();
            },

            /**
             *点击添加按钮，弹出弹窗
             */
            async addData(formName) {
                let reply=await verificateDataSourceEdit();
                if (reply.code!==200){
                    this.titleMess = '新增数据源';
                    this.addDatacenterDialogVisible = true;
                    this.datasource = {id: '', name: '', driverClass: '', jdbcUrl: '', datasourceUser: '', password: ''};
                }else {
                    this.$notify.error({
                        title: '',
                        message: reply.msg
                    });
                }

            },
            /**
             * 连接测试功能
             */
            testConnect(formName) {
                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });

                const set = this.$refs;
                set[formName].validate(async (valid) => {
                    if (valid) {
                        let reply =await testConnectDataSource(this.datasource);
                        if (reply.code == 200) {
                            loading.close();
                            this.$notify.success({
                                title: '',
                                message: '测试链接成功！'
                            });
                        } else {
                            loading.close();
                            console.log(reply.msg);
                            this.$notify.error({
                                title: '',
                                message: reply.msg
                            });
                            //this.search();
                        }
                        //this.$refs[formName].resetFields();

                    } else {
                        console.log('error submit!!');
                        loading.close();
                        this.$notify.error({
                            title: '',
                            message: '验证失败！'
                        });
                        return false;
                    }
                });
            },


            /**
             * 新增提交数据到后台
             * @param formName
             */
            addSubmitForm(formName) {

                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                const set = this.$refs;
                set[formName].validate( async(valid) => {
                    if (valid) {
                        let reply =await addDataSource(this.datasource);
                        if (reply.code == 200) {
                            this.search();
                            loading.close();
                            this.$notify.success({
                                title: '',
                                message: '新增成功！'
                            });
                        } else {
                            loading.close();
                            this.$notify.error({
                                title: '',
                                message: '新增失败！系统内部错误，请联系管理员'
                            });
                        }
                        this.addDatacenterDialogVisible = false;
                        //this.$refs['datasource1'].resetFields();
                    } else {
                        loading.close();
                        console.log(this.reportdata);
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            /**
             * 编辑当前数据,弹出弹框
             */
            editData(tableData) {
                this.search();
                this.titleMess = '编辑数据源';
                this.datasource = tableData;
                this.datasource.password = '';
                this.centerDialogVisible = true;

            },
            /**
             * 提交数据到后台
             * @param formName
             */
            editSubmitForm(formName) {
                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                const set = this.$refs;
                set[formName].validate(async(valid) => {
                    if (valid) {
                        let reply =await editDataSource(this.datasource);
                        if (reply.code == 200) {
                            loading.close();
                            this.$notify.success({
                                title: '',
                                message: '编辑成功！'
                            });
                            this.centerDialogVisible = false;
                        } else {
                            loading.close();
                            this.$notify.error({
                                title: '',
                                message: '编辑失败！'
                            });
                            this.search();
                        }
                        this.$refs[formName].resetFields();

                    } else {
                        loading.close();
                        console.log(this.reportdata);
                        console.log('error submit!!');
                        return false;
                    }
                });


            },

            /**
             * 删除当前数据源
             * @param formName
             */
            async  deleteSubmitForm(index,tableData){
                const loading = this.$loading({
                    lock: true,
                    text: '加载中...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                let reply =await deleteDataSource(tableData);
                if (reply.code == 200) {
                    this.tableData.splice(index, 1);
                    loading.close();
                    this.$notify.success({
                        title: '',
                        message: '删除成功！'
                    });
                } else {
                    loading.close();
                    this.$notify.error({
                        title: '',
                        message: reply.msg
                    });
                }
            }

        }


    }
</script>

<style scoped>


</style>